package com.zxl.always.on.display.ui.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import com.zxl.always.on.display.constant.LockerSetting;
import com.zxl.always.on.display.model.TimerHelper;
import com.zxl.always.on.display.tools.LogUtils;
import com.zxl.always.on.display.ui.helper.ScreenHelper;

/**
 * Created by Administrator on 2018/2/24.
 */

public class ScreenReceiver extends BroadcastReceiver implements OnHomeKeyListener {

    private Context mContext;

    private boolean mIsRegister;

    public static boolean mIsScreenOn;

    public static boolean mIsShown;

    private ScreenHelper mScreenHelper;

    public ScreenReceiver(Context mContext, ScreenHelper mScreenHelper) {
        this.mContext = mContext;
        this.mScreenHelper = mScreenHelper;
        new HomeKeyMonitor(mContext, this);
    }

    public void registerReceiver() {
        if (!mIsRegister) {
            try {
                mIsRegister = true;
                IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
                intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
                mContext.registerReceiver(this, intentFilter);
            } catch (Exception e) {
                mIsRegister = false;
            }
        }
    }

    public void unregisterReceiver() {
        if (mIsRegister) {
            try {
                mIsRegister = false;
                mContext.unregisterReceiver(this);
            } catch (Exception e) {
                mIsRegister = true;
            }
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (null == intent) {
            return;
        }
        if (!LockerSetting.sIsSwitchStatus) {
            LogUtils.d("开关关闭");
            return;
        }

        if (!TimerHelper.isInDate()) {
            LogUtils.d("不在显示时间内");
            return;
        }

        String action = intent.getAction();
        LogUtils.d("action : " + action);
        if (Intent.ACTION_SCREEN_OFF.equals(action)) {
            mIsScreenOn = false;
            if (mIsShown) {
                LogUtils.d("closeScreen");
                mScreenHelper.closeScreen();
                mIsShown = false;
            } else {
                LogUtils.d("showScreen");
                mScreenHelper.showScreen();
                mIsShown = true;
            }
        } else if (Intent.ACTION_SCREEN_ON.equals(action)) {
            mIsScreenOn = true;
        }
        Log.d("LogUtils", action + ", " + mIsScreenOn + ", " + mIsShown);
    }

    @Override
    public void onHome() {
        if (mIsShown) {
            mScreenHelper.closeScreen();
            mIsShown = false;
        }
    }

    @Override
    public void onRecentApps() {

    }

    @Override
    public void onLock() {

    }
}
